package com.fa4j.common.base.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.fa4j.common.base.exception.CommonServerError;

import java.util.Optional;

public interface CommonSettingsService {

    Optional<String> getSettings(String code);

    default <T> Optional<T> getSettings(String code, TypeReference<T> typeReference) {
        return getSettings(code).map(json -> JSON.parseObject(json, typeReference));
    }

    default <T> Optional<T> getSettings(String code, Class<T> clazz) {
        return getSettings(code).map(json -> JSON.parseObject(json, clazz));
    }

    default <T> Optional<T> getSettings(Class<T> clazz) {
        return getSettings(clazz.getSimpleName(), clazz);
    }

    default <T> T getSettingsWithDefault(Class<T> clazz) {
        return getSettings(clazz)
                .orElseGet(() -> {
                    try {
                        return clazz.getConstructor().newInstance();
                    } catch (Exception e) {
                        throw CommonServerError.INTERNAL_SERVER_ERROR.build("获取默认配置对象异常", e);
                    }
                });
    }


}
